package com.woniuxy01;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 作者
 * @create 2025-08-11 9:37
 */
public class JdbcUtil {

    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        String className="com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql:///db2";
        String user="root";
        String password="123";
        Class.forName(className);
        return DriverManager.getConnection(url, user, password);
    }

    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) throws SQLException {
        if(rs!=null) {
            rs.close();
        }
        if(ps!=null) {
            ps.close();
        }
        if(conn!=null) {
            conn.close();
        }
    }

    //封装执行增删改
    public static int executeUpdate(Connection connection, String sql,Object... obj) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < obj.length; i++) {
            preparedStatement.setObject(i + 1, obj[i]);
        }
        int count = preparedStatement.executeUpdate();
        close(connection, preparedStatement, null);
        return count;
    }

    //封装执行查询
    // --返回ResultSet，
    // --返回数据对象，或者数据集合
    // 反射
    public static <T> List<T> executeUpdate(
            Connection connection,Class<T> clazz , String sql,  Object... obj) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        List<T> list = new ArrayList<T>();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < obj.length; i++) {
            preparedStatement.setObject(i + 1, obj[i]);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        //查询数据，ResultSet----->对象（对象集合）
        //读取每行数据
        //1、创建对象
        //2、给属性赋值  metaData可以获取表中的列名，根据列名查找属性，用该列的值给对象的属性赋值
//        ResultSetMetaData metaData = resultSet.getMetaData();
//        for(int i=0;i<metaData.getColumnCount();i++){
//            System.out.println(metaData.getColumnName(i+1));
//        }
        while (resultSet.next()) {
            //读取每行数据,使用反射创建对象
            T t=clazz.newInstance();
            //给属性赋值  metaData可以获取表中的列名，
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                // 获取列名
                String columnName = metaData.getColumnName(i + 1);
                // 根据列名查找属性
                Field field = clazz.getDeclaredField(columnName);
                //用该列的值给对象的属性赋值
                field.setAccessible(true);
                field.set(t, resultSet.getObject(columnName));
            }
            list.add(t);
        }
        return list;
    }
}
